package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.Nuyoah
 * @Date2025/5/20 21:51
 */
@Service
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    /**
     * 新增套餐
     *
     * @param setmealDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setCreateUser(BaseContext.getCurrentId());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        setmealMapper.insert(setmeal);
        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        if (setmealDishList != null && setmealDishList.size() > 0){
            setmealDishList.forEach(d->{
                d.setSetmealId(setmealId);
            });
            setmealDishMapper.insertBatch(setmealDishList);
        }
        //清理缓存
        String key = "setmeal:"+setmealDTO.getCategoryId();
        redisTemplate.delete(key);


    }

    /**
     * 分页查询
     *
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        PageHelper.startPage(setmealPageQueryDTO.getPage(),setmealPageQueryDTO.getPageSize());
        List<Setmeal> list = setmealMapper.pageQuery(setmealPageQueryDTO);
        Page<Setmeal> page = (Page<Setmeal>) list;
        return new PageResult(page.getTotal(),page.getResult());
    }


    /**
     * 批量删除套餐
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        setmealMapper.delete(ids);
        setmealDishMapper.deleteBySetmealId(ids);
        if (CollectionUtils.isNotEmpty(ids)){
            for (Long id : ids) {
                Setmeal setmeal = setmealMapper.getById(id);
                String key  = "setmeal:"+setmeal.getCategoryId();
                redisTemplate.delete(key);
            }
        }
    }

    /**
     * 根据id查询套餐
     *
     * @param id
     * @return
     */
    @Override
    public SetmealVO getById(Long id) {
        SetmealVO setmealVO = new SetmealVO();
        Setmeal setmeal = setmealMapper.getById(id);
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setSetmealDishes(setmealDishMapper.getBySetmealId(id));
        return setmealVO;

    }

    /**
     * 修改套餐
     *
     * @param setmealDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        setmealMapper.update(setmeal);
        List<SetmealDish> setmealDishList = setmealDTO.getSetmealDishes();
        // 判断如果不为空,则删除套餐和菜品的关联数据
        if (setmealDishList != null && setmealDishList.size() > 0){
            setmealDishMapper.deleteSetmealById(setmealDTO.getId());
        }
        setmealDishList.forEach(sd->{
            sd.setSetmealId(setmealDTO.getId());
        });
        // 批量插入菜品和套餐关系数据
        setmealDishMapper.insertBatch(setmealDishList);
        //清理缓存
        String key = "setmeal:"+setmealDTO.getCategoryId();
        redisTemplate.delete(key);
    }

    /**
     * 套餐起售停售
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        setmealMapper.update(setmeal);
        //清理缓存
        Setmeal setmealMapperById = setmealMapper.getById(id);
        String key = "setmeal:"+setmealMapperById.getCategoryId();
        redisTemplate.delete(key);
    }
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {
        String key = "setmeal:"+setmeal.getCategoryId();
        //1.判断Redis缓存中是否有数据
        ListOperations<String, String> opsForList = redisTemplate.opsForList();
        List<String> stringList = opsForList.range(key, 0, -1);
        if (CollectionUtils.isNotEmpty(stringList)){
            List<Setmeal> list = stringList.stream()
                    .map(x -> JSON.parseArray(x, Setmeal.class))
                    .flatMap(List::stream)
                    .collect(Collectors.toList());
            return list;
        }

        //2.如果Redis缓存中没有,则从数据库中查询
        List<Setmeal> list = setmealMapper.list(setmeal);

        //3.将查询到的数据存入到Redis缓存中
        redisTemplate.opsForList().leftPushAll(key,JSON.toJSONString(list));

        return list;
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {

        return setmealMapper.getDishItemBySetmealId(id);


    }

}
